import storage from "@/utils/storage";
import store from '@/store/index'
import { getStorage } from '@/utils/storage';
import baseApi from "@/config/baseApi.js";


const requestFun = (url, method, data, header) => {
	return new Promise((resolve, reject) => {
		uni.request({
			header: header ?? {
				'Authorization': `${storage.getToken()}`,
				'content-type': 'application/json',
			},
			url: baseApi.baseApi + url,
			data,
			method,
			success(res) {
				if (res.statusCode === 200) {
					if (res.data?.code == undefined || res.data.code == 200) {
						resolve(res.data)
					}else if ( res.data.code == 408) {
						uni.showToast({
							title: `${res.data.msg}`,
							icon: 'error'
						})
						setTimeout(() => {
							uni.navigateTo({ url: '/pages/login/login' })
						}, 2000)
					}else if ( res.data.code == 400) {
						uni.showToast({
							title: `${res.data.msg}`,
							icon: 'error'
						})
						setTimeout(() => {
							uni.navigateTo({ url: '/pages/login/register' })
						}, 2000)
					}else {
						if (res.data?.msg) {
							uni.showToast({
								title: res.data.msg,
								icon: 'error'
							})
						}
						reject(res.data)
					}
				} else if (res.statusCode === 401||res.statusCode === 424) {
					if (res.data?.code == '4012') {
						uni.showToast({
							title: '用户信息未授权',
							icon: 'error'
						})
						setTimeout(() => {
							uni.navigateTo({ url: '/pages/login/login' })
						}, 2000)
					} else {
						const token = getStorage('token');
						const sessionInfo = getStorage('sessionInfo');
						if (token && sessionInfo) {
							reloadRequest(url, method, data, header).then(res => {
								resolve(res)
							})
						} else {
							uni.showToast({
								title: '登录过期',
								icon: 'error'
							})
							setTimeout(() => {
								uni.navigateTo({ url: '/pages/login/login' })
							}, 2000)
						}
					}
				}  else {
					if (res.data?.msg) {
						uni.showToast({
							title: res.data.msg,
							icon: 'error'
						})
					}
					reject(res.data)
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

// 重新发起请求
const reloadRequest = (url, method, data, header) => {
	return new Promise(async (resolve, reject) => {
		try {
			await store.dispatch('setLoginInfo')
			const resp = await requestFun(url, method, data, header)
			resolve(resp)
		} catch (err) {
			reject()
			console.log(err);
		}
	})
}

const uploadFun = (path) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseApi.uploadFileApi + '/api/sys-user/uploadAvatar',
			filePath: path,
			method:'post',
			header: {
				'Authorization': `${storage.getToken()}`,
			},
			name: 'file',
			success: (res) => {
				console.log('res',res.data);
				const responseData = JSON.parse(res.data)
				if (res.statusCode == 200 && responseData.code == 200) {
					resolve(responseData.data)
				} else if (res.statusCode === 401 || res.statusCode === 424) {
					uni.showToast({
						title: '登录过期',
						icon: 'error'
					})
					setTimeout(() => {
						uni.navigateTo({ url: '/login/index' })
					}, 2000)
				} else {
					uni.showToast({
						title: '上传出错了',
						icon: 'error'
					})
					reject(res)
				}
			},
			fail: (err) => {
				console.log('fail',err);
				reject(err)
			}
		});
	})
}

const request = {
	get: (url, data = '') => {
		if (data !== '') {
			let keyList = Object.keys(data)
			keyList.forEach((el, index) => {
				if (data[el]) {
					url += (index === 0 ? '?' : '&') + el + '=' + data[el]
				}
			})
		}
		return requestFun(url, 'get')
	},
	post: (url, data = {}, header) => {
		return requestFun(url, 'post', data, header)
	},
	put: (url, data = {}, header) => {
		return requestFun(url, 'put', data, header)
	},
	delete: (url, data='', header) => {
		return requestFun(url, 'delete', data, header)
	},
	uploadFile: (path) => uploadFun(path)
}

export default request
